<template>
  <el-dialog title="悬赏详情" :visible.sync="dialogVisible" width="600px" ref="dialog">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>{{ task.title }} </span>
      </div>
      <div>
        悬赏金额： <span style="color:#ff4c4c;"> {{ formatReward(task.reward) }} </span> Nas
      </div>
      <div>
        悬赏状态：{{ getTaskStatus(task.finished) }}
      </div>
      <div>
        创建日期：{{ formatTime(task.timestamp) }}
      </div>
      <div>
        创建人：<a v-bind:href="explorer + 'address/' + task.from" target="_blank">{{ task.from }}</a>
      </div>
      <div v-show="task.finished != '0'">
        领取人：<a v-bind:href="explorer + 'address/' + task.to" target="_blank">{{ task.to }}</a>
      </div>
      <div>
        {{ task.content }}
      </div>
      <template v-if="task.finished == '0'">
        <div class="take">
          <el-input v-model="taskCode" placeholder="请输入领奖码">
            <el-button slot="append" @click="onTake">领取悬赏</el-button>
          </el-input>
        </div>
      </template>
    </el-card>
    <div class="result" v-show="success">
      <div>
        <span style="color: red;">请等待钱包确认交易成功</span>，将交易写入区块链。
      </div>
      <div>
        您的交易Hash（点击查看交易状态）:
      </div>
      <div>
        <a v-bind:href="explorer + 'tx/' + txhash" target="_blank">{{ txhash }}</a>
      </div>
    </div>
  </el-dialog>
</template>

<script>
  import Vue from 'vue';
  import util from '../util';
  import ElButton from "../../node_modules/element-ui/packages/button/src/button.vue";

  export default {
    components: {ElButton},
    name: 'TaskDetail',
    props: {
      task: {
        type: Object,
        required: true
      }
    },
    data () {
      return {
        dialogVisible: false,
        explorer: util.config.explorer,
        taskCode: '',
        txhash: '',
        success: false,
      }
    },
    methods: {
      show() {
        console.log('-->cleanStatus');
        this.taskCode = '';
        this.txhash = '';
        this.success = false;
        this.dialogVisible = true;
      },
      getTaskStatus(val) {
        if (val == '0') {
          return '进行中';
        }
        else {
          return '已完成';
        }
      },
      formatReward(r) {
        return util.nebulas.Unit.fromBasic(r, 'nas').toString();
      },
      formatTime(t) {
        var date = new Date(t*1000);
        var hours = date.getHours();
        var minutes = "0" + date.getMinutes();
        var seconds = "0" + date.getSeconds();
        var year = date.getFullYear();
        var month = "0" + date.getMonth();
        var day = "0" + date.getDate();
        var formattedTime =  year + '-' + month + '-' + day + ' ' + hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);
        return formattedTime;
      },
      onTake() {
        if (this.taskCode.length < 1) {
          this.$message({
            showClose: true,
            message: '请输入有效的领奖码！',
            type: 'error'
          });
        }
        else {
          var to = util.config.dappaddr;
          var value = 0;
          var callFunc = "take";
          var callArgs = '["' + this.task.txhash + '", "' + this.taskCode + '"]';

          this.listenWallet();
          var serialNumber = util.nebPay.call(to, value, callFunc, callArgs, {
            listener: (data) => {
              if (typeof data === 'object') {
                console.log("listener:" + data);
              } else {
                this.$message({
                  showClose: true,
                  message: '交易被取消，悬赏创建失败！',
                  type: 'error'
                });
              }
            }
          });

        }
      },
      listenWallet() {
        window.addEventListener('message', (resp) => {
          if(resp.data.src !== "content")
            return;
          if(typeof resp.data.resp !== 'object')
            return;
          var key = resp.data.serialNumber;
          var txhash = resp.data.resp.txhash;
          this.txhash = txhash;
          this.success = true;
        });
      }
    }
  };
</script>

<style>
  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }
  .clearfix:after {
    clear: both
  }

  .box-card {
    width: 98%;
    margin: auto;
    margin-top: 0px;
  }

  .take {
    padding-top: 20px;
  }

  .result {
    margin-top: 20px;
    padding: 20px;
  }

</style>
